package com.daocao.common.utils;

import cn.hutool.core.util.ObjectUtil;
import com.daocao.common.constants.HttpStatus;
import com.daocao.common.entity.vo.LoginUserVo;
import com.daocao.common.exception.ServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;


/**
 * 获取用户信息工具类
 */
public class DaoCaoSecurityUtil {

    /**
     * 获取 Authentication
     * 通过 SecurityContextHolder 中的 Context 获取
     *
     * @return Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取当前登录用户
     *
     * @return LoginUserVo
     */
    public static LoginUserVo getLoginUser() {
        return (LoginUserVo) getAuthentication().getPrincipal();
    }

    /**
     * 获取用户 ID
     *
     * @return (Long) LoginUserVo.getId
     */
    public static Long getUserId() {
        Long userId = getLoginUser().getId();
        if (ObjectUtil.isNull(userId)) {
            throw new ServiceException(HttpStatus.FORBIDDEN, "");
        }
        return userId;
    }

    public static String getUsername() {
        String username = getLoginUser().getUsername();
        if (ObjectUtil.isNull(username)) {
            throw new ServiceException(HttpStatus.FORBIDDEN, "");
        }
        return username;
    }
}
